require 'rubygems'
require 'macaddr'
require 'uuidtools'
require 'hpricot'

include UUIDTools
include ScraperHtml

class Product < ActiveRecord::Base
  belongs_to :category,:counter_cache=>true
  belongs_to :brand
  has_and_belongs_to_many :properties, :join_table => "holds"
  has_and_belongs_to_many :collectors,:class_name=>"User",:join_table => "favorites"
  has_many:comments
  attr_accessor :active
  before_create :create_uuid,:set_active_date
  before_update :re_active

  GEOMETRY_IMAGE_SIZE = "300X300"
  MEDIUM_IMAGE_SIZE = "100X100"
  THUMB_IMAGE_SIZE = "50X50"


  file_column :image_url, :magick => {:geometry=>GEOMETRY_IMAGE_SIZE,
    :versions => { "thumb" => THUMB_IMAGE_SIZE,"medium" => MEDIUM_IMAGE_SIZE}
  }

  file_column :image_url2, :magick => {:geometry=>GEOMETRY_IMAGE_SIZE,
    :versions => { "thumb" => THUMB_IMAGE_SIZE,"medium" => MEDIUM_IMAGE_SIZE}
  }

  file_column :image_url3, :magick => {:geometry=>GEOMETRY_IMAGE_SIZE,
    :versions => { "thumb" => THUMB_IMAGE_SIZE,"medium" => MEDIUM_IMAGE_SIZE}
  }

 
  def create_uuid
    #    UUID.mac_address = Mac.addr
    #    self.uuid = UUID.timestamp_create().to_s
    self.uuid = UUIDTools::UUID.random_create().to_s
  end

  def self.maintain(new_category_id,old_category_id)
    if new_category_id != old_category_id
      Category.update_counters old_category_id, :products_count=>-1
      Category.update_counters new_category_id, :products_count=>1
    end
  end

  def self.all_active(limit=1)
    self.find(:all,
      :conditions=>"DATE_ADD(`active_date`,INTERVAL `live_date` DAY) > now()",
      :order=>'sort_order desc,id desc',
      :limit=>limit)
  end

  def self.recommendation(limit=1)
    self.find(:all,
      :conditions=>"DATE_ADD(`active_date`,INTERVAL `live_date` DAY) > now() and recommend = 1",
      :order=>'sort_order desc,id desc',
      :limit=>limit)
  end

  def self.all_inactive(limit=1)
    self.find(:all,
      :conditions=>"DATE_ADD(`active_date`,INTERVAL `live_date` DAY) < now()",
      :order=>'sort_order desc',
      :limit=>limit)
  end
  
  def last
    (self.active_date  - DateTime.now).to_i + self.live_date
  end

  def find_by_brand_and_category(category_id,brand_id)
    find_by_sql(["SELECT DISTINCT p.*
FROM products p, categories c
WHERE  p.category_id = c.id
AND (
c.id = ?
)
and p.brand_id = ? and
DATE_ADD(`active_date`,INTERVAL `live_date` DAY) > now()
ORDER BY p.sort_order DESC",category_id,brand_id])
  end

  def self.recommend
    self.find(:all,:conditions=>['recommend = 1 and active = 1'])
  end

  def set_active_date
    self.active_date = DateTime.now
  end

  def re_active
    if self.active
      set_active_date
    end
  end

  def self.search_without_brand(keyword,price="",brand_id="",page=1)
    price_limit_low = 0
    price_limit_height = 9999
    price = price.to_i

    case price
    when 1, 2
      price_limit_height = price * 50
    when 4,6
      price_limit_low = (price -2) * 50
      price_limit_height = price * 50
    when 7
      price_limit_low = 300
    else
    end

    sql_arry = ["(products.name like ? or model like ? or products.description like ? or brands.name like ? or brands.name like ?)
 and (DATE_ADD(products.active_date,INTERVAL products.live_date DAY) > now()) and (retail_price between ? and ?)",
      "%#{keyword}%","%#{keyword}%","%#{keyword}%","%#{keyword}%","%#{keyword}%",price_limit_low,price_limit_height]


    if  brand_id !=""
      sql_arry[0] <<  " and (brand_id = ?)"
      sql_arry << brand_id
    end

    return self.paginate :include=>:brand,:conditions=>sql_arry,
      :page => page,:per_page => 5
  end

  def self.scraper(site,category_id,brand_id)
    result = 0
   
    doc = open(site[:url]){ |f| Hpricot(f)}
    iconv=Iconv.new("UTF-8//IGNORE",site[:encoding])
    #从xpath中获取数据

    if !site[:name].blank?
      pname = iconv.iconv(doc.search((site[:name])).inner_text)
      pname =  pname.gsub(Regexp.new(site[:name_filter]),"") if !site[:name_filter].blank?
    else
      pname = Category.find(category_id).name
    end

    if !site[:unit].blank?
      unit = iconv.iconv(doc.search((site[:unit])).inner_text)
      unit =  unit.gsub(Regexp.new(site[:unit_filter]),"") if !site[:unit_filter].blank?
    end

    if !site[:size].blank?
      size = iconv.iconv(doc.search((site[:size])).inner_text)
      size =  size.gsub(Regexp.new(site[:size_filter]),"") if !site[:size_filter].blank?
    end

    if !site[:official_price].blank?
      official_price = iconv.iconv(doc.search((site[:official_price])).inner_text)
      official_price =  official_price.gsub(Regexp.new(site[:official_price_filter]),"") if !site[:official_price_filter].blank?
    end

    if !site[:cost_price].blank?
      cost_price = iconv.iconv(doc.search((site[:cost_price])).inner_text)
      cost_price =  cost_price.gsub(Regexp.new(site[:cost_price_filter]),"") if !site[:cost_price_filter].blank?
    end



    description = ""
    description = iconv.iconv(doc.search(site[:desc1]).to_html) if !site[:desc1].blank?
    description.gsub!(Regexp.new(site[:desc_filter]),site[:desc_replace]) if !site[:desc_filter].blank?
    description.gsub!(Regexp.new(site[:desc_filter1]),site[:desc_replace1]) if !site[:desc_filter1].blank?



    unless site[:image].blank?
      image_tag =  doc.search(site[:image]).to_html
      image_url = /(src=")((.)+?)"/.match(image_tag).values_at(2).to_s
      image_url.gsub!("..","")
      site_root = /http:\/\/.+?\//.match(site[:url]).values_at(0).to_s
      image_url = site_root+image_url if !image_url.include?("http")
    end



    product = Product.new(:brand_id => brand_id,
      :category_id=>category_id,
      :name=>pname,
      :size=>size,
      :unit=>unit,
      :official_price=>official_price,
      :cost_price=>cost_price,
      :retail_price=>(cost_price.to_i * site[:times].to_f).to_i,
      :description=>description,
      :purchase_url=>site[:url]
    )
    if product.save
      if image_url
        image_path = save_image(image_url,"product",product.id.to_s)
        sql = ActiveRecord::Base.connection();
        sql.update "UPDATE products SET image_url='#{File.basename(image_path)}' WHERE id=#{product.id}";
      end
      result += 1
    end
    return result
  end

  def self.save_image(image_url,type_path,id)
    begin
      img = open(image_url){|f|f.read}
    rescue
      logger.error("can't open #{image_url}")
    else
      app_root = File.expand_path(RAILS_ROOT)
      img_extension = /\.([^.]+)$/.match(image_url).values_at(0).to_s
      image_dir = "#{app_root}/public/#{type_path}/image_url/#{id}"
      Dir.mkdir(image_dir,0775)
      image_path = "#{image_dir}/#{id}#{img_extension}"

      open(image_path,"wb"){|f|
        f.write(img)
      }
      #小图
      thumb = ImageList.new(image_path)
      thumb.resize_to_fit!(Product::THUMB_IMAGE_SIZE.to_i,Product::THUMB_IMAGE_SIZE.to_i)
      Dir.mkdir("#{File.dirname(image_path)}/thumb",0775)
      thumb.write("#{File.dirname(image_path)}/thumb/#{File.basename(image_path)}")
      #中图
      medium = ImageList.new(image_path)
      medium.resize_to_fit!(Product::MEDIUM_IMAGE_SIZE.to_i,Product::MEDIUM_IMAGE_SIZE.to_i)
      Dir.mkdir("#{File.dirname(image_path)}/medium",0775)
      medium.write("#{File.dirname(image_path)}/medium/#{File.basename(image_path)}")
      #大图
      ImageList.new(image_path).resize_to_fit!(Product::GEOMETRY_IMAGE_SIZE.to_i,Product::GEOMETRY_IMAGE_SIZE.to_i)
    end
    return image_path
  end


end
